
package com.be.beadmin.project.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.project.dto.input.BatchPlanDto;
import com.be.beadmin.project.dto.input.BatchPlanInfoFormDto;
import com.be.beadmin.project.dto.input.InfoAndPage;
import com.be.beadmin.project.dto.input.PlanStageDto;
import com.be.beadmin.project.dto.output.*;
import com.be.beadmin.project.entity.*;
import com.be.beadmin.project.mapper.BatchPlanMapper;
import com.be.beadmin.project.mapper.BatchPlanMapperEx;
import com.be.beadmin.project.mapper.PlanStageMapper;
import com.be.beadmin.project.mapper.PlanStageMapperEx;
import com.be.beadmin.project.repository.*;
import com.be.beadmin.project.service.BatchPlanService;
import com.be.beadmin.project.service.BatchProductService;
import com.be.beadmin.project.service.PlanStageService;
import com.be.beadmin.service.entity.DictData;
import com.be.beadmin.service.entity.DictType;
import com.be.beadmin.service.repository.DictDataRepository;
import com.be.beadmin.service.repository.DictTypeRepository;
import com.be.beadmin.service.service.DictDataService;
import com.be.beadmin.service.service.SerialNumberService;
import com.be.beadmin.service.util.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @description 服务实现
* @author ljh
* @date 2023-02-05
**/
@Service
@RequiredArgsConstructor
public class BatchPlanServiceImpl implements BatchPlanService {

    @Autowired
    private BatchPlanRepository batchPlanRepository;
    @Autowired
    private MasterPlanRepository masterPlanRepository;
    @Autowired
    private BatchProductRepository batchProductRepository;
    @Autowired
    private BatchPlanMapper batchPlanMapper;
    @Autowired
    private BatchPlanMapperEx batchPlanExMapper;
    @Autowired
    private DictTypeRepository dictTypeRepository;
    @Autowired
    private DictDataService dictDataService;
    @Autowired
    private InfoRepository infoRepository;
    @Autowired
    private ProductInfoRepository productInfoRepository;
    @Autowired
    private ProductTotalInfoRepository productTotalInfoRepository;
    @Autowired
    private BatchProductService batchProductService;
    @Autowired
    private SerialNumberService serialNumberService;

    @Autowired
    private PlanStageRepository planStageRepository;
    @Autowired
    private PlanStageService planStageService;
    @Autowired
    private PlanStageMapperEx planStageMapperEx;
    @Autowired
    private PlanStageMapper planStageMapper;
    @Autowired
    private DictDataRepository dictDataRepository;

    @Override
    public Page<BatchPlanEx> getBatchPlanByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<BatchPlan> page = batchPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(BatchPlan_.delete), 0); //过滤为0
//                    criteriaBuilder.like(root.get(BatchPlan_.delete),"%"+name+"%");
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(BatchPlan_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<BatchPlanEx> page1 = page.map(new Function<BatchPlan, BatchPlanEx>() {
                @Override
                public BatchPlanEx apply(BatchPlan batchPlan) {
                    Info infoByIdAndDelete = infoRepository.findInfoByIdAndDelete(batchPlan.getInfoId(), 0);
                    PlanStage productionSplit = planStageRepository.findPlanStageByPlanIdAndStageNameAndDelete(batchPlan.getId(), "生产分料", 0);
                    if (infoByIdAndDelete == null) {
                        return null;
                    }
                    BatchPlanEx batchPlanEx = batchPlanExMapper.toEntity(batchPlan);
                    batchPlanEx.setProjectCode(infoByIdAndDelete.getProjectCode());
                    batchPlanEx.setProjectName(infoByIdAndDelete.getProjectName());
                    batchPlanEx.setProductionSplit(productionSplit.getStagePlanEndTime());
                    return batchPlanEx;

                }
            });
        return page1;
    }


    /**
     * 根据id获取批次计划
     *
     * @param batchPlanId
     * @return
     */
    @Override
    public BatchPlan getBatchPlanById(String batchPlanId) {
        BatchPlan batchPlan = batchPlanRepository.findBatchPlanByIdAndDelete(batchPlanId, 0);
        return batchPlan;
    }

    /**
     * @param batchPlanDto
     */
    @Override
    public void addBatchPlan(BatchPlanDto batchPlanDto) {

    }

    @Override
    public int updateBatchPlanCount(String masterPlanId) {
        int batchCount = batchPlanRepository.countBatchPlanByMasterPlanIdAndDelete(masterPlanId, 0);
        batchPlanRepository.updateBatchPlanCountByMasterPlanIdAndDelete(batchCount, masterPlanId, 0);

//        masterPlanRepository.updateBatchPlanCountByIdAndDelete(batchCount,masterPlanId,0);
        return batchCount;
    }

    public BatchPlan countProductType(BatchPlan batchPlan) {
        // 统计每种柜体的数量 C、P、B、OTHERS
        for (String type : dictDataService.getDictDataKeyByDictTypeName("柜体类型")) {
            int count = batchProductRepository.countBatchProductsByBatchPlanIdAndProductTypeAndDelete(batchPlan.getId(), type, 0);
            switch (type) {
                case "柜体":
                    batchPlan.setCabinetCount(count);
                    break;
                case "箱体":
                    batchPlan.setBoxCount(count);
                    break;
                case "安装板":
                    batchPlan.setOperationCount(count);
                    break;
                case "其他":
                    batchPlan.setOthersCount(count);
                    break;
                default:
                    break;
            }
        }
        return batchPlan;
    }

    @Transactional
    @Override
    public BatchPlan addBatchPlan(BatchPlanInfoFormDto batchPlaninfoDto) {


        // 主计划
        MasterPlan masterPlan = masterPlanRepository.findMasterPlanByIdAndDelete(batchPlaninfoDto.getMasterPlanId(), 0);
        if (ObjectUtil.isEmpty(masterPlan)) {
            throw new BeadminException("没有找到主计划"); //没有找到主计划
        }

        if (batchPlaninfoDto.getBatchDeliveryDate().compareTo(masterPlan.getDeliveryDate()) > 0) {
            throw new BeadminException("批次交付日期晚于项目交付日期"); //此计划时间晚于主计划
        }
//        BatchPlan batchPlanResult = batchPlanRepository.findBatchPlanByIdAndDelete(batchPlaninfoDto.get, 0);
//        if(ObjectUtil.isNotEmpty(batchPlanResult)) {
//            System.out.println("masterPlan:"+masterPlan);
//            return -1; //已存在批次计划
//        }
        Info info = infoRepository.findInfoByIdAndDelete(masterPlan.getInfoId(), 0);
        if (ObjectUtil.isEmpty(info)) {
            throw new BeadminException("未找到项目信息"); //未找到项目信息
        }


        // 设置批次计划基本信息
        BatchPlan batchPlan = new BatchPlan();
        BatchPlan result = batchPlanRepository.findBatchPlanByCurrentBatchAndMasterPlanIdAndDelete(batchPlaninfoDto.getCurrentBatch(), batchPlaninfoDto.getMasterPlanId(), 0);
        if (result != null) { //当前批次已导入
            throw new BeadminException("当前批次已导入");
        }


        batchPlan.setMasterPlanId(batchPlaninfoDto.getMasterPlanId());
        batchPlan.setMemo(batchPlaninfoDto.getMemo());
//        batchPlan.setProjectName(masterPlaninfoDto.getProjectName());
        batchPlan.setBatchDeliveryDate(batchPlaninfoDto.getBatchDeliveryDate());
        batchPlan.setInfoDeliveryDate(masterPlan.getDeliveryDate());
        if (batchPlaninfoDto.getIsInit() == 1) { // 初始批次
            batchPlan.setCurrentBatch(1);
            batchPlan.setBatchCount(1);
        } else { // 其他批次
            batchPlan.setCurrentBatch(batchPlaninfoDto.getCurrentBatch());
            batchPlan.setBatchCount(batchPlaninfoDto.getCurrentBatch());
        }
        batchPlan.setInfoId(info.getId());
        batchPlan.setProjectName(info.getProjectName());
        batchPlan.setBatchPlanCode(masterPlan.getMasterPlanCode() + "." + serialNumberService.getNextSnByCode(info.getId()+ "_BP_Code"));

        // 保存批次计划
        BatchPlan saveBatchPlan = batchPlanRepository.save(batchPlan);

        // 设置各阶段时长
        setDurationOfEachPhase(saveBatchPlan,batchPlaninfoDto.getBatchDeliveryDate());


        PlanStage stage = getStageByBatchPlanAndStageName(saveBatchPlan, "柜体设计");

        //***** 批次柜体录入
        if (batchPlaninfoDto.getIsInit() == 1) {
            // 仅有一个批次
            batchProductRepository.updateBatchPlanIdByInfoIdAndDelete(saveBatchPlan.getId(), info.getId(), 0);
            batchProductRepository.updateBatchDeliveryDateByInfoIdAndDelete(saveBatchPlan.getBatchDeliveryDate(), info.getId(), 0);
            return saveBatchPlan;
        }

        // 常规创建批次计划
        List<String> selectedBatchProductIds = batchPlaninfoDto.getSelectedBatchProductId(); //批次柜体的简单信息
        // 将柜体绑在批次计划中
        for (String batchProductId : selectedBatchProductIds) {
            BatchProduct batchProduct = batchProductRepository.findBatchProductByIdAndDelete(batchProductId, 0);
            batchProduct.setBatchPlanId(saveBatchPlan.getId());
            batchProduct.setPlanDesignStartDate(stage.getStagePlanStartTime());
            batchProduct.setPlanDesignEndDate(stage.getStagePlanEndTime());
            batchProduct.setActualKickoffStartDate(stage.getStageEndTime());
            batchProduct.setBatchPlanId(saveBatchPlan.getId());
            batchProduct.setBatchDeliveryDate(batchPlaninfoDto.getBatchDeliveryDate());

            batchProductRepository.save(batchProduct);

        }
        // 统计每种柜体的数量 C、P、B、OTHERS
        saveBatchPlan = countProductType(saveBatchPlan);
        // 统计批次总数
        int batchCount = batchPlanRepository.countBatchPlanByMasterPlanIdAndDelete(masterPlan.getId(), 0);
        saveBatchPlan.setBatchCount(batchCount + 1);
        BatchPlan save = batchPlanRepository.save(saveBatchPlan);
        // 更新批次总数
        int batchTotalCount = updateBatchPlanCount(masterPlan.getId());
        // 更新已下发柜体的批次信息
        updateBatchProductBatchInfo(masterPlan.getId(),batchTotalCount,null);

        return save;
    }

    /**
     *  1. 增加批次后, 修改已下发至设计的柜体总批次信息
     *  2. 删除某批次后，修改该批次之后的批次当前批次数量 : eg. 删除第三批次，第四批次变为第三批次
     */
    @Override
    public void updateBatchProductBatchInfo(String masterPlanId, Integer batchTotalCount, Integer currentBatch){

        // state ！= 0, 表示已下发的批次
        List<BatchPlan> plans = batchPlanRepository.findBatchPlanByMasterPlanIdAndStateNotAndDelete(masterPlanId, 0, 0);

        List<BatchProduct> batchProducts = new ArrayList<>();

        for (BatchPlan plan: plans){

            batchProducts.addAll(batchProductRepository.findBatchProductByBatchPlanIdAndDelete(plan.getId(),0));
        }

        List<BatchProduct> batchProductsUpdated = batchProducts.stream().peek(s -> {
            if (s.getBatchCountInfo()!=null){
                String[] split = s.getBatchCountInfo().split("/");
                if (currentBatch != null && Integer.parseInt(split[0]) > currentBatch){
                    split[0] = String.valueOf(Integer.parseInt(split[0]) - 1);
                }
                s.setBatchCountInfo(split[0] + "/" + batchTotalCount);
            }
        }).collect(Collectors.toList());

        batchProductRepository.saveAll(batchProductsUpdated);
    }

    /**
     * 修改一个项目批次计划的柜体信息
     *
     * @param batchPlaninfoDto
     */
    @Override
    public int updateBatchPlanProduct(BatchPlanInfoFormDto batchPlaninfoDto) {

        // 主计划
        MasterPlan masterPlan = masterPlanRepository.findMasterPlanByIdAndDelete(batchPlaninfoDto.getMasterPlanId(), 0);
        int batchCount = batchPlanRepository.countBatchPlanByMasterPlanIdAndDelete(masterPlan.getId(), 0);
        if (ObjectUtil.isEmpty(masterPlan)) {
            return -2; //没有找到getProductBomOverviewByPage主计划
        }
        Info info = infoRepository.findInfoByIdAndDelete(masterPlan.getInfoId(), 0);
        if (ObjectUtil.isEmpty(info)) {
            return -3; //未找到项目信息
        }
        if (batchPlaninfoDto.getBatchDeliveryDate().compareTo(masterPlan.getDeliveryDate()) > 0) {
            throw new BeadminException("批次交付日期不能晚于项目交付日期");
//            return -4; //此计划时间晚于主计划
        }
        if (batchPlaninfoDto.getCurrentBatch() > batchCount) {
            return -5; //当前批次数不能大于批次总数
        }

//        if ()
        // 设置批次计划基本信息
        // 修改前的计划
        BatchPlan newBatchPlan = batchPlanRepository.findBatchPlanByIdAndDelete(batchPlaninfoDto.getBatchPlanId(), 0);
        System.out.println("newBatchPlan:" + newBatchPlan);
        System.out.println("batchPlaninfoDto:" + batchPlaninfoDto);

        newBatchPlan.setBatchDeliveryDate(batchPlaninfoDto.getBatchDeliveryDate());
        newBatchPlan.setMemo(batchPlaninfoDto.getMemo());
//        BatchPlan batchPlannew = setDurationOfEachPhase(newBatchPlan);
        BatchPlan saveBatchPlan = batchPlanRepository.save(newBatchPlan); //更改存入数据库

        PlanStage stage = getStageByBatchPlanAndStageName(saveBatchPlan, "柜体设计");
        PlanStage stage2 = getStageByBatchPlanAndStageName(saveBatchPlan, "项目开工");

        // 同步该批次的发货日期 == 批次交付日期, 并做各工序时间倒退，交货日期为第一个
        List<PlanStage> planStages = planStageRepository.findPlanStagesByPlanIdAndDeleteOrderByStageSortDesc(batchPlaninfoDto.getBatchPlanId(),0);
        for (int i = 0; i < planStages.size(); i++) {
            PlanStage planStage = planStages.get(i);
            if (i == 0) {
                planStage.setStagePlanEndTime(DateUtil.computeDate(batchPlaninfoDto.getBatchDeliveryDate(),0));
            } else {
                planStage.setStagePlanEndTime(DateUtil.computeDate(planStages.get(i-1).getStagePlanStartTime(),-1*24));
            }
            planStage.setStagePlanStartTime(DateUtil.computeDate(planStage.getStagePlanEndTime(),-1 * planStage.getStageDuration() *24 ));
        }
        planStageRepository.saveAll(planStages);


//        // 修改前的批次柜体信息
        List<BatchProduct> BatchProducts = batchProductRepository.findBatchProductByBatchPlanIdAndDelete(saveBatchPlan.getId(), 0);

        List<BatchProduct> unallocatedBatchProducts = batchProductRepository.findBatchProductByInfoIdAndBatchPlanIdAndDeleteOrderByCreateTimeDesc(masterPlan.getInfoId(), "-1", 0);

        //        batchProductRepository.findBatchProductByProductTypeAndInfoIdAndDelete();
        // 修改后的批次柜体信息
        List<String> selectedBatchProductId = batchPlaninfoDto.getSelectedBatchProductId();
        BatchProducts.addAll(unallocatedBatchProducts);
        for (BatchProduct oldBatchProduct : BatchProducts) {
            if (selectedBatchProductId.contains(oldBatchProduct.getId())) {
                oldBatchProduct.setBatchPlanId(saveBatchPlan.getId());
                oldBatchProduct.setPlanDesignStartDate(stage.getStagePlanStartTime());
                oldBatchProduct.setPlanDesignEndDate(stage.getStagePlanEndTime());
                oldBatchProduct.setActualKickoffStartDate(stage2.getStagePlanStartTime());
                oldBatchProduct.setBatchDeliveryDate(batchPlaninfoDto.getBatchDeliveryDate());
            } else {
                oldBatchProduct.setBatchPlanId("-1");
                oldBatchProduct.setPlanDesignStartDate(null);
                oldBatchProduct.setPlanDesignEndDate(null);
                oldBatchProduct.setActualKickoffStartDate(null);
                oldBatchProduct.setBatchDeliveryDate(null);
            }

        }
        batchProductRepository.saveAll(BatchProducts);

        // 统计每种柜体的数量 C、P、B、OTHERS
        saveBatchPlan = countProductType(saveBatchPlan);
        batchPlanRepository.save(saveBatchPlan);


        return 0;

    }


    /**
     * 根据项目Id获取批次计划分页信息
     *
     * @param infoAndPage
     * @return
     */
    @Override
    public Page<BatchPlanEx> getBatchPlanByPageAndInfoId(InfoAndPage infoAndPage) {

        PageEntity pageEntity = infoAndPage.getPageEntity();
        String infoId = infoAndPage.getInfoId();
        if (infoId == null) throw new BeadminException("需要指定项目Id");
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<BatchPlan> page = batchPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(BatchPlan_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(BatchPlan_.infoId), infoId); //过滤为0
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(BatchPlan_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<BatchPlanEx> page1 = page.map(batchPlanExMapper::toEntity);
        return page1;

    }

    /**
     * 获取批次计划及各阶段分页信息
     *
     * @param infoAndPage
     * @return
     */
    @Override
    public Page<BatchPlanAndStageEx> getBatchPlanAndStageByPageAndInfoId(InfoAndPage infoAndPage) {
        PageEntity pageEntity = infoAndPage.getPageEntity();
        String infoId = infoAndPage.getInfoId();
        if (infoId == null) throw new BeadminException("需要指定项目Id");
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<BatchPlan> page = batchPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(BatchPlan_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(BatchPlan_.infoId), infoId); //过滤为0
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(BatchPlan_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
//        Page<BatchPlanEx> page1 = page.map(batchPlanExMapper::toEntity);
//        return page1;
        Page<BatchPlanAndStageEx> map = page.map(new Function<BatchPlan, BatchPlanAndStageEx>() {
            @Override
            public BatchPlanAndStageEx apply(BatchPlan batchPlan) {
                BatchPlanAndStageEx batchPlanAndStageEx = new BatchPlanAndStageEx();
                List<PlanStage> planStages = planStageRepository.findPlanStagesByPlanIdAndDeleteOrderByStageSort(batchPlan.getId(), 0);
                batchPlanAndStageEx.setBatchPlanEx(batchPlanExMapper.toEntity(batchPlan));
                batchPlanAndStageEx.setPlanStagesEx(planStageMapperEx.toEntity(planStages));
                return batchPlanAndStageEx;
            }
        });

        return map;
    }

    /**
     * 修改一个批次计划各阶段时间
     *
     * @param planStageDtos
     */
    @Transactional
    @Override
    public void updateBatchPlanStageTime(List<PlanStageDto> planStageDtos) {
        if (planStageDtos.size() == 0) {
            return;
        }
        if (planStageDtos.size() == 0) throw new BeadminException("没有传入阶段计划时间参数为空");

        List<PlanStage> planStages = new ArrayList<>();
        // 检查一下顺序是否正确
        planStageDtos.forEach(planStageDto -> {
//            PlanStage planStageByIdAndDelete = planStageRepository.findPlanStageByIdAndDelete(planStageDto.getId(), 0);

            PlanStage planStage = planStageService.toEntity(planStageDto);

            planStages.add(planStage);
        });
        // 排一下序
        planStages.sort(new Comparator<PlanStage>() {
            @Override
            public int compare(PlanStage o1, PlanStage o2) {
                return o1.getStageSort().compareTo(o2.getStageSort());
            }
        });

        // 检测一下时间， 开始不能晚于结束， 所有时间不能晚于交付时间
        PlanStage planStage1 = planStages.get(0);
        PlanStage planStagePre = null;
//        PlanStage planStageByIdAndDelete1 = planStageRepository.findPlanStageByIdAndDelete(planStageDto1.getId(), 0);
        BatchPlan batchPlan = batchPlanRepository.findBatchPlanByIdAndDelete(planStage1.getPlanId(), 0);
        if (batchPlan == null) {
            throw new BeadminException("未找到这批阶段的批次计划");
        }

        // 获取改批次下的所有柜体,用以更新日期
        List<BatchProduct> products = batchProductRepository.findBatchProductByBatchPlanIdAndDelete(batchPlan.getId(), 0);

        // 获取项目交付日期
        MasterPlan masterPlan = masterPlanRepository.findMasterPlanByIdAndDelete(batchPlan.getMasterPlanId(), 0);
        Date deliveryDate = DateUtil.transDateFormat(masterPlan.getDeliveryDate());

        for (int i = 0; i < planStages.size(); i++) {
            PlanStage planStage = planStages.get(i);


//            PlanStage planStageByIdAndDelete = planStageRepository.findPlanStageByIdAndDelete(planStage.getId(), 0);
//            if (planStageByIdAndDelete == null) {
//                throw new BeadminException("未找到ID为" + planStageByIdAndDelete.getId() + "的项目阶段");
//            }
//            if (ObjectUtil.isEmpty(planStage.getStagePlanStartTime()))
//                planStage.setStagePlanStartTime(planStage.getStagePlanStartTime());
//            if (ObjectUtil.isEmpty(planStageDto.getStagePlanEndTime()))
//                planStageDto.setStagePlanEndTime(planStageByIdAndDelete.getStagePlanStartTime());
//            if (ObjectUtil.isEmpty(planStageDto.getStageSort()))
//                planStageDto.setStageSort(planStageByIdAndDelete.getStageSort());
            if (DateUtil.transDateFormat(planStage.getStagePlanStartTime()).after(deliveryDate))
                throw new BeadminException(planStage.getStageName() + "计划开始日期不能超过项目交付日期");
            if (DateUtil.transDateFormat(planStage.getStagePlanEndTime()).after(deliveryDate))
                throw new BeadminException(planStage.getStageName() + "计划结束日期不能超过项目交付日期");
            if (DateUtil.transDateFormat(planStage.getStagePlanStartTime()).after(DateUtil.transDateFormat(planStage.getStagePlanEndTime())))
                throw new BeadminException(planStage.getStageName() + "计划开始日期不能晚于计划结束日期");
//            if ()

            if (i>0){
                planStagePre =  planStages.get(i - 1);
                if (planStagePre == null) {
                    throw new BeadminException("未找到前一个计划");
                }
                if (planStage.getStagePlanStartTime().before(planStagePre.getStagePlanEndTime()))
                    throw new BeadminException(planStage.getStageName() + "计划开始日期不能早于"+planStagePre.getStageName()+"计划结束日期");
            }

            if (planStage.getStageStartTime() != null && DateUtil.transDateFormat(planStage.getStageStartTime()).after(deliveryDate))
                throw new BeadminException(planStage.getStageName() + "实际开始日期不能超过项目交付日期");
            if (planStage.getStageEndTime() != null && DateUtil.transDateFormat(planStage.getStageEndTime()).after(deliveryDate))
                throw new BeadminException(planStage.getStageName() + "实际结束日期不能超过项目交付日期");
            if (planStage.getStageStartTime() != null && planStage.getStageEndTime() != null && DateUtil.transDateFormat(planStage.getStageStartTime()).after(DateUtil.transDateFormat(planStage.getStageEndTime())))
                throw new BeadminException(planStage.getStageName() + "实际开始日期不能晚于实际结束日期");


            switch (planStage.getStageName()) {
                case "发货日期":
                    // 若更改批次发货结束日期，同步更改到下发柜体的批次交付日期
                    products = products.stream().peek(s -> s.setBatchDeliveryDate(planStage.getStagePlanEndTime())).collect(Collectors.toList());
                    break;

                case "柜体设计":
                    // 若更改批次柜体设计相关日期，同步更改到下发柜体中
                    products = products.stream().peek(s -> {
                        s.setPlanDesignStartDate(planStage.getStagePlanStartTime());
                        s.setPlanDesignEndDate(planStage.getStagePlanEndTime());
                        s.setActualKickoffStartDate(planStage.getStageEndTime());
                    }).collect(Collectors.toList());
                    break;
                case "生产分料":
                    // 若更改批次分料计划开始日期，同步更改到下发柜体分料日期
                    products = products.stream().peek(s -> s.setStageDosingStartTime(planStage.getStagePlanStartTime())).collect(Collectors.toList());
                    break;
            }
        }
        batchProductRepository.saveAll(products);
//        保存
        planStageRepository.saveAll(planStages);
    }

    /**
     * 根据计划及阶段名获取该阶段
     *
     * @param batchPlan
     * @param stageName
     * @return
     */
    @Override
    public PlanStage getStageByBatchPlanAndStageName(BatchPlan batchPlan, String stageName) {
//        BatchPlan batchPlan = batchPlanRepository.findBatchPlanByIdAndDelete(batchProduct.getBatchPlanId(), 0);
        PlanStage stage = planStageRepository.findPlanStageByPlanIdAndStageNameAndDelete(batchPlan.getId(), stageName, 0);
        if (stage == null) {
            stage = new PlanStage(batchPlan.getId(), "默认阶段", Integer.MAX_VALUE, null, null, null, null, 5);
//            throw new BeadminException("未找到批次计划"+batchPlan.getBatchPlanCode()+"的"+stageName+"阶段，将返回一个默认阶段，阶段时长为5天");
        }
        return stage;
    }

    /**
     * 获取所有批次计划及各阶段分页信息
     *
     * @param pageEntity
     * @return
     */
    @Override
    public Page<BatchPlanAndStageEx> getBatchPlanAndStageByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<BatchPlan> page = batchPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(BatchPlan_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(BatchPlan_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
//        Page<BatchPlanEx> page1 = page.map(batchPlanExMapper::toEntity);
//        return page1;
        Page<BatchPlanAndStageEx> map = page.map(new Function<BatchPlan, BatchPlanAndStageEx>() {
            @Override
            public BatchPlanAndStageEx apply(BatchPlan batchPlan) {
                BatchPlanAndStageEx batchPlanAndStageEx = new BatchPlanAndStageEx();
                List<PlanStage> planStages = planStageRepository.findPlanStagesByPlanIdAndDeleteOrderByStageSort(batchPlan.getId(), 0);
                BatchPlanEx batchPlanEx = batchPlanExMapper.toEntity(batchPlan);
                MasterPlan masterPlan = masterPlanRepository.findMasterPlanByIdAndDelete(batchPlan.getMasterPlanId(), 0);
                if (masterPlan == null) {
                    return null;
                }
                Info info = infoRepository.findInfoByIdAndDelete(masterPlan.getInfoId(), 0);
                if (info == null) {
                    return null;
                }
                batchPlanEx.setProjectCode(info.getProjectCode());
                batchPlanAndStageEx.setBatchPlanEx(batchPlanEx);
                batchPlanAndStageEx.setPlanStagesEx(planStageMapperEx.toEntity(planStages));
                return batchPlanAndStageEx;
            }
        });

        return map;
    }

    /**
     * 获取该批次计划所有的柜体数量
     *
     * @param batchPlanId
     */
    @Override
    public int countProductByBatchPlan(String batchPlanId) {

        return batchProductRepository.countBatchProductsByBatchPlanIdAndDelete(batchPlanId,0);
    }

    /**
     * 获取该批次计划所有的柜体数量
     *
     * @param batchPlanId
     * @param type
     */
    @Override
    public int countProductByBatchPlanAndType(String batchPlanId, String type) {
        return batchProductRepository.countBatchProductsByBatchPlanIdAndProductTypeAndDelete(batchPlanId,type,0);
    }

    @Override
    public int countUnAssginProduct(String infoId) {
        int products = batchProductRepository.countBatchProductsByInfoIdAndBatchPlanIdAndDelete(infoId, "-1", 0);
        return products;
    }

    @Override
    public List<String> getBatchPlanCode() {
        List<String> batchPlanCodeList = batchPlanRepository.findBatchPlanCodeByDelete(0);
        return batchPlanCodeList;
    }

//    /**
//     * 获取批次计划的简单分页信息，生产排程中需要用到
//     *
//     * @param pageEntity
//     * @return
//     */
//    @Override
//    public Object getBatchPlanInProductByPage(PageEntity pageEntity) {
//        getBatchPlanByPage(pageEntity)
//        return null;
//    }

    /**
     * 添加批次计划的各阶段时间
     *
     * @param batchPlan
     * @return
     */
    public BatchPlan setDurationOfEachPhase(BatchPlan batchPlan, Date batchDeliveryDate) {

        // 查询工时
        // 设置工时
        DictType workTimeDt = dictTypeRepository.findDictTypeByDictNameAndDelete("默认工期", 0);
        if (workTimeDt == null) {
            throw new BeadminException("未找到默认工期字典字段");
        }
        List<PlanStage> planStages = new ArrayList<>();
        List<DictData> dataList = dictDataRepository.findDictDataByDictTypeIdAndDeleteOrderByDictSortDesc(workTimeDt.getId(), 0);

        for (int i = 0; i < dataList.size(); i++) {

            DictData dictData = dataList.get(i);
            PlanStage planStage = planStageRepository.findPlanStageByPlanIdAndStageNameAndDelete(batchPlan.getId(), dictData.getKeyName(), 0);
            if (planStage == null) {
                planStage = new PlanStage();

            }
            planStage.setPlanId(batchPlan.getId()); // 计划id
            planStage.setStageSort(dictData.getDictSort()); // 阶段排序
            planStage.setStageName(dictData.getKeyName()); // 阶段名
            planStage.setStageDuration(Integer.parseInt(dictData.getKeyValue())); //阶段时长
            if (i == 0) {
                // 前端传交货日期
                planStage.setStagePlanEndTime(DateUtil.computeDate(batchDeliveryDate, 0));
            } else {
                planStage.setStagePlanEndTime(DateUtil.computeDate(planStages.get(i - 1).getStagePlanStartTime(), -1 * 24));
            }
            planStage.setStagePlanStartTime(DateUtil.computeDate(planStage.getStagePlanEndTime(), -1 * planStage.getStageDuration() * 24));
            planStages.add(planStage);
        }
        planStages.sort(new Comparator<PlanStage>() {
            @Override
            public int compare(PlanStage o1, PlanStage o2) {
                return o1.getStageSort().compareTo(o2.getStageSort());
            }
        });

        planStageRepository.saveAll(planStages);

        return batchPlan;
    }

    public void computeUnallocateProduct(String infoId, String masterPlanId) {
        List<ProductInfo> productInfos = productInfoRepository.findProductInfoByInfoIdAndDelete(infoId, 0);
        List<String> batchPlanIds = batchPlanRepository.findIdByMasterPlanIdAndDelete(masterPlanId, 0);
        batchProductRepository.findBatchProductByBatchPlanIdInAndDelete(batchPlanIds, 0);
        List<String> produceTypes = batchProductService.getProduceType();
        produceTypes.forEach(produceType -> {
            int beforeCount = productInfoRepository.countProductInfoByProductTypeAndDelete(produceType, 0);
            int count = batchProductRepository.countBatchProductByBatchPlanIdInAndProductTypeAndDelete(batchPlanIds, produceType, 0);

        });

    }

    /**
     * 生成初始批次计划
     *
     * @param infoDto
     * @return
     */
    @Override
    public int addInitBatchPlan(BatchPlanInfoFormDto infoDto) {
        return 0;
    }

    /**
     * 生成初始批次计划
     *
     * @param masterPlanId
     * @return
     */
    @Override
    public int addInitBatchPlan(String masterPlanId) {

        MasterPlan masterPlan = masterPlanRepository.findMasterPlanByIdAndDelete(masterPlanId, 0);
        /**
         * 条件判断
         */
        BatchPlanInfoFormDto batchPlanInfoSimpDto = new BatchPlanInfoFormDto();
        batchPlanInfoSimpDto.setCurrentBatch(1);
        batchPlanInfoSimpDto.setMasterPlanId(masterPlanId);
        batchPlanInfoSimpDto.setInfoDeliveryDate(masterPlan.getDeliveryDate());
        // 初始批次交付日期默认为项目交付日期
        batchPlanInfoSimpDto.setBatchDeliveryDate(masterPlan.getDeliveryDate());
        batchPlanInfoSimpDto.setIsInit(1);
//        List<BatchProduceSimpDto> batchProduceSimpDtos = new ArrayList<>();
//        BatchProduceSimpDto batchProduceSimpDto = new BatchProduceSimpDto();
//        productInfos.forEach(productInfo -> {
//            batchProduceSimpDto.setProductCode(productInfo.getProductCode());
//            batchProduceSimpDto.setProductType(productInfo.getProductType());
//            batchProduceSimpDto.setIsStandard(BigDecimal.valueOf(productInfo.getIsStandard()));
//            batchProduceSimpDtos.add(batchProduceSimpDto);
//        });
//        batchPlanInfoSimpDto.setBatchProduceSimpDtos(batchProduceSimpDtos);
        addBatchPlan(batchPlanInfoSimpDto);

        return 0;
    }



    @Override
    public void delBatchPlans(List<String> ids) {
    }

    /**
     * 生成添加批次计划的表单项
     *
     * @param infoId
     * @return
     */
    @Override
    public BatchPlanInfoFormEx genAddBatchPlanForm(String infoId) {

        MasterPlan masterPlan = masterPlanRepository.findMasterPlanByInfoIdAndDelete(infoId, 0);
        int count = batchPlanRepository.countBatchPlanByMasterPlanIdAndDelete(masterPlan.getId(), 0);
        BatchPlanInfoFormEx batchPlanInfoSimpEx = new BatchPlanInfoFormEx();
        batchPlanInfoSimpEx.setMasterPlanId(masterPlan.getId());
        batchPlanInfoSimpEx.setCurrentBatch(count + 1);
        batchPlanInfoSimpEx.setBatchCount(count + 1);
        batchPlanInfoSimpEx.setInfoDeliveryDate(masterPlan.getDeliveryDate());
        batchPlanInfoSimpEx.setBatchDeliveryDate(masterPlan.getDeliveryDate());
        List<BatchProduct> batchProducts = batchProductRepository.findBatchProductByInfoIdAndBatchPlanIdAndDeleteOrderByCreateTimeDesc(infoId, "-1", 0);
        List<BatchProductSimp> batchProductSimpExes = new ArrayList<>();
        if (batchProducts.size() == 0) {
            return null;
        }
        for (BatchProduct bp :
                batchProducts) {
            BatchProductSimp batchProductSimpEx = new BatchProductSimp();
            batchProductSimpEx.setInfoId(bp.getInfoId());
            batchProductSimpEx.setProductCode(bp.getProductCode());
            batchProductSimpEx.setProductType(bp.getProductType());
//            batchProductSimpEx.setIsSelected(0);
            batchProductSimpEx.setIsStandard(bp.getIsStandard());
            batchProductSimpEx.setBatchProductId(bp.getId());
            batchProductSimpEx.setProductDesc(bp.getProductDesc());
            batchProductSimpExes.add(batchProductSimpEx);

        }
////        List<ProductTotalInfo> productTotalInfos = productTotalInfoRepository.findProductTotalInfoByInfoIdAndDelete(masterPlan.getInfoId(),0);
//        System.out.println("List<ProductTotalInfo> productTotalInfos:"+productTotalInfos);
//        List<BatchProduceSimpDto> batchProduceSimpDtos = new ArrayList<>();
//        productTotalInfos.forEach(productTotalInfo -> {
//            BatchProduceSimpDto bp = new BatchProduceSimpDto();
//            bp.setProductType(productTotalInfo.getProductType());
//            bp.setProductQty(0);
//            bp.setMaxQty(productTotalInfo.getProductQty());
//            bp.setIsStandard(BigDecimal.valueOf(productTotalInfo.getIsStandard()));
//            bp.setUnstandardName(productTotalInfo.getUnstandardName());
//            batchProduceSimpDtos.add(bp);
//        });
//        batchPlanInfoSimpEx.setBatchProduceSimpDtos(batchProduceSimpDtos);
        batchPlanInfoSimpEx.setBatchProductSimps(batchProductSimpExes);

        return batchPlanInfoSimpEx;
    }

    /**
     * 生成修改批次计划的表单项
     *
     * @param batchPlanId
     * @return
     */
    @Override
    public BatchPlanInfoFormEx genUpdateBatchPlanForm(String batchPlanId) {

        BatchPlan batchPlan = batchPlanRepository.findBatchPlanByIdAndDelete(batchPlanId, 0);
        if (batchPlan == null) {
            return null;
        }
        int count = batchPlanRepository.countBatchPlanByMasterPlanIdAndDelete(batchPlan.getMasterPlanId(), 0);
        MasterPlan masterPlan = masterPlanRepository.findMasterPlanByIdAndDelete(batchPlan.getMasterPlanId(), 0);
        BatchPlanInfoFormEx batchPlanInfoSimpEx = new BatchPlanInfoFormEx();
        batchPlanInfoSimpEx.setMasterPlanId(batchPlan.getMasterPlanId());
        batchPlanInfoSimpEx.setBatchPlanId(batchPlanId);
        batchPlanInfoSimpEx.setBatchDeliveryDate(batchPlan.getBatchDeliveryDate());
        batchPlanInfoSimpEx.setCurrentBatch(batchPlan.getCurrentBatch());
        batchPlanInfoSimpEx.setBatchCount(count);
        batchPlanInfoSimpEx.setMemo(batchPlan.getMemo());

        batchPlanInfoSimpEx.setInfoDeliveryDate(masterPlan.getDeliveryDate());
        // 添加下面的表单项
//        List<BatchProduceSimpDto> batchProduceSimpDtos =  batchProductService.getProductByBatchPlan(batchPlanId);
//        List<BatchProduceSimpDto> batchProduceSimpDtos =  new ArrayList<>();
//
////        for ()
//        List<ProductTotalInfo> productTotalInfos = productTotalInfoRepository.findProductTotalInfoByInfoIdAndDelete(masterPlan.getInfoId(),0);
//        for(ProductTotalInfo productTotalInfo:productTotalInfos){
//            BatchProduceSimpDto bp = new BatchProduceSimpDto();
//            int count1 = batchProductRepository.countBatchProductByBatchPlanIdAndProductTypeAndIsStandardAndDelete(batchPlanId,productTotalInfo.getProductType(),productTotalInfo.getIsStandard(),0);
//            if (count1 == 0){
//                continue;
//            }
//            bp.setProductType(productTotalInfo.getProductType());
//            bp.setProductQty(count1);
//            bp.setMaxQty(productTotalInfo.getProductQty());
//            bp.setIsStandard(BigDecimal.valueOf(productTotalInfo.getIsStandard()));
//            bp.setUnstandardName(productTotalInfo.getUnstandardName());
//            batchProduceSimpDtos.add(bp);
//        };
//        batchPlanInfoSimpEx.setBatchProduceSimpDtos(batchProduceSimpDtos);
        List<BatchProduct> batchProductNotSelected = batchProductRepository.findBatchProductByInfoIdAndBatchPlanIdAndDeleteOrderByCreateTimeDesc(masterPlan.getInfoId(), "-1", 0);
        List<BatchProduct> batchProductSelected = batchProductRepository.findBatchProductByInfoIdAndBatchPlanIdAndDeleteOrderByCreateTimeDesc(masterPlan.getInfoId(), batchPlanId, 0);

        List<BatchProductSimp> batchProductSimpExes = new ArrayList<>();
        List<String> selectedProductId = new ArrayList<>();

        for (BatchProduct bp :
                batchProductSelected) {
            BatchProductSimp batchProductSimpEx = new BatchProductSimp();
            batchProductSimpEx.setInfoId(bp.getInfoId());
            batchProductSimpEx.setProductCode(bp.getProductCode());
            batchProductSimpEx.setProductType(bp.getProductType());
            batchProductSimpEx.setProductDesc(bp.getProductDesc());
            batchProductSimpEx.setIsSelected(1);
            batchProductSimpEx.setIsStandard(bp.getIsStandard());
            batchProductSimpEx.setBatchProductId(bp.getId());
            batchProductSimpExes.add(batchProductSimpEx);
            selectedProductId.add(bp.getId());
        }
        for (BatchProduct bp :
                batchProductNotSelected) {
            BatchProductSimp batchProductSimpEx = new BatchProductSimp();
            batchProductSimpEx.setInfoId(bp.getInfoId());
            batchProductSimpEx.setProductCode(bp.getProductCode());
            batchProductSimpEx.setProductType(bp.getProductType());
            batchProductSimpEx.setProductDesc(bp.getProductDesc());
//            batchProductSimpEx.setIsSelected(0);
            batchProductSimpEx.setIsStandard(bp.getIsStandard());
            batchProductSimpEx.setBatchProductId(bp.getId());
            batchProductSimpExes.add(batchProductSimpEx);
        }
        batchPlanInfoSimpEx.setBatchProductSimps(batchProductSimpExes);
        batchPlanInfoSimpEx.setSelectedproductId(selectedProductId);
        return batchPlanInfoSimpEx;
    }

    /**
     * 修改一个项目批次计划的基础时间
     *
     * @param batchPlanDto
     */
    @Override
    public void updateBatchPlanTime(BatchPlanDto batchPlanDto) {
//        BatchPlan result = batchPlanRepository.findBatchPlanByIdAndDelete(batchPlanDto.getId(),0);
//        BatchPlan batchPlan = batchPlanMapper.toEntity(batchPlanDto);
////        result = updateResult(result,batchPlan);
//        batchPlanRepository.save(result);
    }
//    private BatchPlan updateResult(BatchPlan result, BatchPlan batchPlan) {
//        if ( batchPlan == null ) {
//            return result;
//        }
//
//        if ( batchPlan.getSerialNo() != null ) {
//            result.setSerialNo( batchPlan.getSerialNo() );
//        }
//        if ( batchPlan.getMasterPlanId() != null ) {
//            result.setMasterPlanId( batchPlan.getMasterPlanId() );
//        }
//        if ( batchPlan.getCurrentBatch() != null ) {
//            result.setCurrentBatch( batchPlan.getCurrentBatch() );
//        }
//        if ( batchPlan.getBatchPlanCode() != null ) {
//            result.setBatchPlanCode( batchPlan.getBatchPlanCode() );
//        }
//        if ( batchPlan.getBatchDeliveryDate() != null ) {
//            result.setBatchDeliveryDate( batchPlan.getBatchDeliveryDate() );
//        }
//        if ( batchPlan.getPlanKickoffStartDate() != null ) {
//            result.setPlanKickoffStartDate( batchPlan.getPlanKickoffStartDate() );
//        }
//        if ( batchPlan.getPlanKickoffEndDate() != null ) {
//            result.setPlanKickoffEndDate( batchPlan.getPlanKickoffEndDate() );
//        }
//        if ( batchPlan.getPlanKickoffPeriod() != 0 ) {
//            result.setPlanKickoffPeriod( batchPlan.getPlanKickoffPeriod() );
//        }
//        if ( batchPlan.getPlanDesignStartDate() != null ) {
//            result.setPlanDesignStartDate( batchPlan.getPlanDesignStartDate() );
//        }
//        if ( batchPlan.getPlanDesignEndDate() != null ) {
//            result.setPlanDesignEndDate( batchPlan.getPlanDesignEndDate() );
//        }
//        if ( batchPlan.getPlanDesignPeriod() != 0 ) {
//            result.setPlanDesignPeriod( batchPlan.getPlanDesignPeriod() );
//        }
//        if ( batchPlan.getPlanPurchaseStartDate() != null ) {
//            result.setPlanPurchaseStartDate( batchPlan.getPlanPurchaseStartDate() );
//        }
//        if ( batchPlan.getPlanPurchaseEndDate() != null ) {
//            result.setPlanPurchaseEndDate( batchPlan.getPlanPurchaseEndDate() );
//        }
//        if ( batchPlan.getPlanPurchasePeriod() != 0 ) {
//            result.setPlanPurchasePeriod( batchPlan.getPlanPurchasePeriod() );
//        }
//        if ( batchPlan.getPlanLogisticStartDate() != null ) {
//            result.setPlanLogisticStartDate( batchPlan.getPlanLogisticStartDate() );
//        }
//        if ( batchPlan.getPlanLogisticEndDate() != null ) {
//            result.setPlanLogisticEndDate( batchPlan.getPlanLogisticEndDate() );
//        }
//        if ( batchPlan.getPlanLogisticPeriod() != 0 ) {
//            result.setPlanLogisticPeriod( batchPlan.getPlanLogisticPeriod() );
//        }
//        if ( batchPlan.getPlanOrderStartDate() != null ) {
//            result.setPlanOrderStartDate( batchPlan.getPlanOrderStartDate() );
//        }
//        if ( batchPlan.getPlanOrderEndDate() != null ) {
//            result.setPlanOrderEndDate( batchPlan.getPlanOrderEndDate() );
//        }
//        if ( batchPlan.getPlanOrderPeriod() != 0 ) {
//            result.setPlanOrderPeriod( batchPlan.getPlanOrderPeriod() );
//        }
//        if ( batchPlan.getPlanInboundStartDate() != null ) {
//            result.setPlanInboundStartDate( batchPlan.getPlanInboundStartDate() );
//        }
//        if ( batchPlan.getPlanInboundEndDate() != null ) {
//            result.setPlanInboundEndDate( batchPlan.getPlanInboundEndDate() );
//        }
//        if ( batchPlan.getPlanInboundPeriod() != 0 ) {
//            result.setPlanInboundPeriod( batchPlan.getPlanInboundPeriod() );
//        }
//        if ( batchPlan.getPlanPackStartDate() != null ) {
//            result.setPlanPackStartDate( batchPlan.getPlanPackStartDate() );
//        }
//        if ( batchPlan.getPlanPackEndDate() != null ) {
//            result.setPlanPackEndDate( batchPlan.getPlanPackEndDate() );
//        }
//        if ( batchPlan.getPlanPackPeriod() != 0 ) {
//            result.setPlanPackPeriod( batchPlan.getPlanPackPeriod() );
//        }
//        if ( batchPlan.getPlanDeliveryStartDate() != null ) {
//            result.setPlanDeliveryStartDate( batchPlan.getPlanDeliveryStartDate() );
//        }
//        if ( batchPlan.getPlanDeliveryEndDate() != null ) {
//            result.setPlanDeliveryEndDate( batchPlan.getPlanDeliveryEndDate() );
//        }
//        if ( batchPlan.getPlanDeliveryPeriod() != 0 ) {
//            result.setPlanDeliveryPeriod( batchPlan.getPlanDeliveryPeriod() );
//        }
//        if ( batchPlan.getPlanReceiptStartDate() != null ) {
//            result.setPlanReceiptStartDate( batchPlan.getPlanReceiptStartDate() );
//        }
//        if ( batchPlan.getPlanReceiptEndDate() != null ) {
//            result.setPlanReceiptEndDate( batchPlan.getPlanReceiptEndDate() );
//        }
//        if ( batchPlan.getPlanReceiptPeriod() != 0 ) {
//            result.setPlanReceiptPeriod( batchPlan.getPlanReceiptPeriod() );
//        }
//        if ( batchPlan.getPlanInstallStartDate() != null ) {
//            result.setPlanInstallStartDate( batchPlan.getPlanInstallStartDate() );
//        }
//        if ( batchPlan.getPlanInstallEndDate() != null ) {
//            result.setPlanInstallEndDate( batchPlan.getPlanInstallEndDate() );
//        }
//        if ( batchPlan.getPlanInstallPeriod() != 0 ) {
//            result.setPlanInstallPeriod( batchPlan.getPlanInstallPeriod() );
//        }
//        if ( batchPlan.getPlanCommissionStartDate() != null ) {
//            result.setPlanCommissionStartDate( batchPlan.getPlanCommissionStartDate() );
//        }
//        if ( batchPlan.getPlanCommissionEndDate() != null ) {
//            result.setPlanCommissionEndDate( batchPlan.getPlanCommissionEndDate() );
//        }
//        if ( batchPlan.getPlanCommissionPeriod() != 0 ) {
//            result.setPlanCommissionPeriod( batchPlan.getPlanCommissionPeriod() );
//        }
//        if ( batchPlan.getPlanFacStartDate() != null ) {
//            result.setPlanFacStartDate( batchPlan.getPlanFacStartDate() );
//        }
//        if ( batchPlan.getPlanFacEndDate() != null ) {
//            result.setPlanFacEndDate( batchPlan.getPlanFacEndDate() );
//        }
//        if ( batchPlan.getPlanFacPeriod() != 0 ) {
//            result.setPlanFacPeriod( batchPlan.getPlanFacPeriod() );
//        }
////        result.setIsReleased( batchPlan.getIsReleased() );
//
//        if ( batchPlan.getActualKickoffStartDate() != null ) {
//            result.setActualKickoffStartDate( batchPlan.getActualKickoffStartDate() );
//        }
//        if ( batchPlan.getActualKickoffEndDate() != null ) {
//            result.setActualKickoffEndDate( batchPlan.getActualKickoffEndDate() );
//        }
//        if ( batchPlan.getActualKickoffPeriod() != 0 ) {
//            result.setActualKickoffPeriod( batchPlan.getActualKickoffPeriod() );
//        }
//        if ( batchPlan.getActualDesignStartDate() != null ) {
//            result.setActualDesignStartDate( batchPlan.getActualDesignStartDate() );
//        }
//        if ( batchPlan.getActualDesignEndDate() != null ) {
//            result.setActualDesignEndDate( batchPlan.getActualDesignEndDate() );
//        }
//        if ( batchPlan.getActualDesignPeriod() != 0 ) {
//            result.setActualDesignPeriod( batchPlan.getActualDesignPeriod() );
//        }
//        if ( batchPlan.getActualPurchaseStartDate() != null ) {
//            result.setActualPurchaseStartDate( batchPlan.getActualPurchaseStartDate() );
//        }
//        if ( batchPlan.getActualPurchaseEndDate() != null ) {
//            result.setActualPurchaseEndDate( batchPlan.getActualPurchaseEndDate() );
//        }
//        if ( batchPlan.getActualPurchasePeriod() != 0 ) {
//            result.setActualPurchasePeriod( batchPlan.getActualPurchasePeriod() );
//        }
//        if ( batchPlan.getActualLogisticStartDate() != null ) {
//            result.setActualLogisticStartDate( batchPlan.getActualLogisticStartDate() );
//        }
//        if ( batchPlan.getActualLogisticEndDate() != null ) {
//            result.setActualLogisticEndDate( batchPlan.getActualLogisticEndDate() );
//        }
//        if ( batchPlan.getActualLogisticPeriod() != 0 ) {
//            result.setActualLogisticPeriod( batchPlan.getActualLogisticPeriod() );
//        }
//        if ( batchPlan.getActualOrderStartDate() != null ) {
//            result.setActualOrderStartDate( batchPlan.getActualOrderStartDate() );
//        }
//        if ( batchPlan.getActualOrderEndDate() != null ) {
//            result.setActualOrderEndDate( batchPlan.getActualOrderEndDate() );
//        }
//        if ( batchPlan.getActualOrderPeriod() != 0 ) {
//            result.setActualOrderPeriod( batchPlan.getActualOrderPeriod() );
//        }
//        if ( batchPlan.getActualInboundStartDate() != null ) {
//            result.setActualInboundStartDate( batchPlan.getActualInboundStartDate() );
//        }
//        if ( batchPlan.getActualInboundEndDate() != null ) {
//            result.setActualInboundEndDate( batchPlan.getActualInboundEndDate() );
//        }
//        if ( batchPlan.getActualInboundPeriod() != 0 ) {
//            result.setActualInboundPeriod( batchPlan.getActualInboundPeriod() );
//        }
//        if ( batchPlan.getActualPackStartDate() != null ) {
//            result.setActualPackStartDate( batchPlan.getActualPackStartDate() );
//        }
//        if ( batchPlan.getActualPackEndDate() != null ) {
//            result.setActualPackEndDate( batchPlan.getActualPackEndDate() );
//        }
//        if ( batchPlan.getActualPackPeriod() != 0 ) {
//            result.setActualPackPeriod( batchPlan.getActualPackPeriod() );
//        }
//        if ( batchPlan.getActualDeliveryStartDate() != null ) {
//            result.setActualDeliveryStartDate( batchPlan.getActualDeliveryStartDate() );
//        }
//        if ( batchPlan.getActualDeliveryEndDate() != null ) {
//            result.setActualDeliveryEndDate( batchPlan.getActualDeliveryEndDate() );
//        }
//        if ( batchPlan.getActualDeliveryPeriod() != 0 ) {
//            result.setActualDeliveryPeriod( batchPlan.getActualDeliveryPeriod() );
//        }
//        if ( batchPlan.getActualReceiptStartDate() != null ) {
//            result.setActualReceiptStartDate( batchPlan.getActualReceiptStartDate() );
//        }
//        if ( batchPlan.getActualReceiptEndDate() != null ) {
//            result.setActualReceiptEndDate( batchPlan.getActualReceiptEndDate() );
//        }
//        if ( batchPlan.getActualReceiptPeriod() != 0 ) {
//            result.setActualReceiptPeriod( batchPlan.getActualReceiptPeriod() );
//        }
//        if ( batchPlan.getActualInstallStartDate() != null ) {
//            result.setActualInstallStartDate( batchPlan.getActualInstallStartDate() );
//        }
//        if ( batchPlan.getActualInstallEndDate() != null ) {
//            result.setActualInstallEndDate( batchPlan.getActualInstallEndDate() );
//        }
//        if ( batchPlan.getActualInstallPeriod() != 0 ) {
//            result.setActualInstallPeriod( batchPlan.getActualInstallPeriod() );
//        }
//        if ( batchPlan.getActualCommissionStartDate() != null ) {
//            result.setActualCommissionStartDate( batchPlan.getActualCommissionStartDate() );
//        }
//        if ( batchPlan.getActualCommissionEndDate() != null ) {
//            result.setActualCommissionEndDate( batchPlan.getActualCommissionEndDate() );
//        }
//        if ( batchPlan.getActualCommissionPeriod() != 0 ) {
//            result.setActualCommissionPeriod( batchPlan.getActualCommissionPeriod() );
//        }
//        if ( batchPlan.getActualFacStartDate() != null ) {
//            result.setActualFacStartDate( batchPlan.getActualFacStartDate() );
//        }
//        if ( batchPlan.getActualFacEndDate() != null ) {
//            result.setActualFacEndDate( batchPlan.getActualFacEndDate() );
//        }
//        if ( batchPlan.getActualFacPeriod() != 0 ) {
//            result.setActualFacPeriod( batchPlan.getActualFacPeriod() );
//        }
//        if ( batchPlan.getMemo() != null ) {
//            result.setMemo( batchPlan.getMemo() );
//        }
//        if ( batchPlan.getReserved() != null ) {
//            result.setReserved( batchPlan.getReserved() );
//        }
//
//
//        return result;
//    }

    @Override
    public void updateBatchPlan(BatchPlanDto batchPlanDto) {
        BatchPlan batchPlan = batchPlanRepository.findBatchPlanById(batchPlanDto.getId());
        batchPlan = batchPlanMapper.toEntity(batchPlanDto);
        batchPlanRepository.save(batchPlan);
    }
}

